package com.jrfid.smartcabinet.demo.ui.add_account

import android.app.Application
import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.blankj.utilcode.util.ToastUtils
import com.jrfid.smartcabinet.demo.R
import com.jrfid.smartcabinet.demo.base.BaseViewModel
import com.jrfid.smartcabinet.demo.db.AppDatabase
import com.jrfid.smartcabinet.demo.db.entity.AccountInfoEntity

class AddAccountViewModel(application: Application, navController: NavController) : BaseViewModel(application, navController) {

    val account = ObservableField("")
    val password = ObservableField("")

    fun onClickBtnSave(view: View) {
        val a = account.get()
        if (a.isNullOrEmpty()) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_account_hint))
            return
        }
        val p = password.get()
        if (p.isNullOrEmpty()) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_password_hint))
            return
        }
        val info = AppDatabase.instance.getAccountInfoDao().findByAccount(a)
        if (info != null) {
            ToastUtils.showShort(getString(R.string.text_account_registered))
            return
        }
        AppDatabase.instance.getAccountInfoDao().insert(AccountInfoEntity().apply {
            this.account = a
            this.password = p
        })
        ToastUtils.showShort(getString(R.string.text_account_register_successfully))
        account.set("")
        password.set("")
    }

    fun onClickBtnBack(view: View) {
        navController.navigateUp()
    }
}